﻿using System;
using System.Runtime.Serialization;
using System.Linq.Expressions;

namespace ExpressionSerialization
{
  [KnownType(typeof(XExpressionList))]
  [DataContract]
  public class XNewArrayExpression : XExpression
  {

    [DataMember]
    public XExpressionList Expressions { get; set; }

    public override void FromExpression(Expression source_)
    {
      base.FromExpression(source_);
      NewArrayExpression exp = source_ as NewArrayExpression;
      Expressions = new XExpressionList(exp.Expressions);
    }

    public override Expression ToExpression(Type dataContract_, System.Collections.Generic.List<ParameterExpression> parameters_)
    {
      if(NodeType == ExpressionType.NewArrayBounds)
        return Expression.NewArrayBounds( GetExpressionType(dataContract_).GetElementType(), Expressions.ToExpressions(dataContract_,parameters_));
      else if(NodeType == ExpressionType.NewArrayInit)
        return Expression.NewArrayInit(GetExpressionType(dataContract_).GetElementType(), Expressions.ToExpressions(dataContract_, parameters_));
      else
        throw new InvalidOperationException("NodeType for NewArrayExpression must be ExpressionType.NewArrayInit or ExpressionType.NewArrayBounds");
    }
  }
}
